function Middleware(...middlewares) {
  // 调用栈
  const stack = middlewares;

  const use = (...middlewares) => {
    stack.push(...middlewares);
  }

  const execute = async (context, callback) => {
    // 当前标记
    let currentIndex = -1;

    // 递归运行中间件函数
    const runner = (index) => {
      // 防止多次调用next
      if (index === currentIndex) {
        throw new Error('next() called multiple times');
      }
      currentIndex = index;
      let middleware = stack[index];

      // middleware最后的回调函数
      if (currentIndex === stack.length) (middleware = callback);

      // middleware不是函数则直接返回
      if (typeof middleware !== 'function') return Promise.resolve(context);

      // 执行中间件
      try {
        // 往中间件传入context和next两个参数
        return Promise.resolve(middleware(context, () => {
          return runner(index + 1);
        }))
      } catch (err) {
        return Promise.reject(err);
      }
    }
    // 启动中间件运行递归
    return runner(0);
  }

  return { use, execute }
}


module.exports = Middleware;